package com.example.jbmsuppliers.sinopec.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.jbmsuppliers.MyDoorPreferTrue;
import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.doorjurisd.DoorOpenBlue;
import com.example.jbmsuppliers.sinopec.utlis.ExitAppUtlis;
import com.example.jbmsuppliers.sinopec.utlis.SaveOpenKeyManage;
import com.example.jbmsuppliers.sinopec.view.DoubleButtonDialog;
import com.example.jbmsuppliers.sinopec.view.MyToast;
import com.example.permission.myjbm.config.Config;
import com.example.permission.myjbm.utils.DensityUtils;
import com.example.permission.myjbm.utils.LoginSharedPreferences;
import com.jbm.jbmsupplier.util.IEGuardKey;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static com.example.jbmsuppliers.sinopec.doorjurisd.IdentificationStepTwoActivity.EXETS;

/**
 * Created by 家帮忙 on 2017/1/13.
 */

public abstract class ActivityUse extends FragmentActivity {

    private FrameLayout content;
//    private FloatingActionButton fb;
    /**
     * 记录当前手指位置在屏幕上的横坐标值
     */
    private float xInScreen;

    /**
     * 记录当前手指位置在屏幕上的纵坐标值
     */
    private float yInScreen;

    /**
     * 记录手指按下时在屏幕上的横坐标的值
     */
    private float xDownInScreen;

    /**
     * 记录手指按下时在屏幕上的纵坐标的值
     */
    private float yDownInScreen;

    /**
     * 记录手指按下时在小悬浮窗的View上的横坐标的值
     */
    private float xInView, yInView;

    /**
     * 记录手指按下时在小悬浮窗的View上的纵坐标的值
     */
    public static int viewWidth;
    private static int statusBarHeight;
    /**
     * 记录小悬浮窗的高度
     */

    public static int viewHeight;
    private RelativeLayout relati;
    int width1,height1;
    private RelativeLayout.LayoutParams mParams;
    private DoorOpenBlue doorOpenBlue;
    public TextView fb;
    private  LoginSharedPreferences  mSharedPreferences;
    private SharedPreferences sharedPreferences,sharedPreferenceslog;

    protected  abstract  int setContentView1();
    protected  abstract  void initView();
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout);
        doorOpenBlue=new DoorOpenBlue(this,null);
        content = (FrameLayout) findViewById(R.id.base_content);
        relati = (RelativeLayout) findViewById(R.id.relati);
        fb=(TextView)findViewById(R.id.textxuanfu);
          mSharedPreferences = new LoginSharedPreferences((this));
        sharedPreferences = getSharedPreferences("dubje", Activity.MODE_PRIVATE);//保存悬浮窗和摇一摇的开关
        sharedPreferenceslog = getSharedPreferences("open_door_log", Activity.MODE_PRIVATE);//保存蓝牙开门反馈给用户展示的信息
        init();
        //初始化悬浮窗当前位置
        content.addView(View.inflate(this,setContentView1(), null));
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean IsFitruexu = sharedPreferences.getBoolean("Isbudjexf", true);
        ArrayList<IEGuardKey> opendoorkey = new SaveOpenKeyManage(this).setgainOpenKey();

        if (mSharedPreferences.getLoginState() != true) {
            fb.setVisibility(View.GONE);
        } else {
            if (IsFitruexu ) {
                fb.setVisibility(View.VISIBLE);

            } else {
                fb.setVisibility(View.GONE);
            }
        }
        if(Config.viewPosition==false){
            distanceX= (-width1+viewWidth);
            distanceY = -(height1/2);
            mSharedPreferences.setShare("floatX",(int)distanceX);
            mSharedPreferences.setShare("floatY",(int)distanceY);
            Config.viewPosition=true;
        }else{
            distanceX =mSharedPreferences.getShare("floatX");
            distanceY =mSharedPreferences.getShare("floatY");
        }
        relati.scrollTo((int)distanceX,(int)distanceY);
        if (opendoorkey==null){
            fb.setVisibility(View.GONE);
            return;}
        if (opendoorkey.size()==0){
            fb.setVisibility(View.GONE);
            return;}
    }

    float distanceX;
    float distanceY;
    private int jilux,jiluy;


    private void init() {
        WindowManager de = getWindowManager();
        DisplayMetrics outMertrics=new DisplayMetrics();
        de.getDefaultDisplay().getMetrics(outMertrics);
        width1 = outMertrics.widthPixels;
        height1=outMertrics.heightPixels;
        fb.measure(0,0);
        viewWidth= DensityUtils.dip2px(ActivityUse.this,fb.getMeasuredWidth()/2);
        viewHeight=DensityUtils.dip2px(ActivityUse.this,fb.getMeasuredHeight());
        mParams= (RelativeLayout.LayoutParams) fb.getLayoutParams();
        fb.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
//                        if(isFirst==false){
//                            xInView = event.getRawX();
//                            yInView = event.getRawY();
//                        }
                        jilux= (int)event.getRawX();
                        jiluy= (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        //  不要直接用getX和getY,这两个获取的数据已经是经过处理的,容易出现图片抖动的情况
                        distanceX = xInView - event.getRawX()+viewWidth/2;
                        distanceY = yInView - event.getRawY()+viewHeight/2;
                        float nextY = fb.getY() - distanceX;
                        float nextX = fb.getX() - distanceY;

//                      // 不能移出屏幕
                        if (nextY < 0) {
                            nextY = 0;
                        } else if (nextY > containerHeight - fb.getHeight()) {
                            nextY = containerHeight - fb.getHeight();
                        }
                        if (nextX < 0)
                            nextX = 0;
                        else if (nextX > containerWidth - fb.getWidth())
                            nextX = containerWidth - fb.getWidth();

                        if((int)distanceX>=0){
                            distanceX=0;
                        } else if((int)distanceX<=(-width1+viewWidth)){

                            distanceX=(-width1+viewWidth);
                        }

                        if((int)distanceY>=0){
                            distanceY=0;
                        }else if((int)distanceY<=(-height1+viewHeight+getStatusBarHeight())){
                            distanceY=(-height1+viewHeight+getStatusBarHeight());
                        }
                        relati.scrollTo((int)distanceX,(int)distanceY);

                        break;
                    case MotionEvent.ACTION_UP:
                        mSharedPreferences.setShare("floatX",(int)distanceX);
                        mSharedPreferences.setShare("floatY",(int)distanceY);
                        if(Math.abs(event.getRawX()-jilux)<5&&Math.abs(event.getRawY()-jiluy)<5){
                            SharedPreferences sharedPreferences = getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE);
                    int open = sharedPreferences.getInt("intopen", 0);
                    if (open != 1) {
                        doorOpenBlue.OpenDoorGather("FloatWindow", fb,getApplicationContext(),ActivityUse.this, null);

                    }else{
                        MyToast.show(ActivityUse.this,"请等待蓝牙恢复",0);
                    }
                            return true;
                        }
//                         如果手指离开屏幕时，xDownInScreen和xInScreen相等，且yDownInScreen和yInScreen相等，则视为触发了单击事件。
                    default:
                        break;
                }
                return true;
            }
        });
    }
    private int containerWidth;
    private int containerHeight;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // 这里来获取容器的宽和高
        if (hasFocus) {
            containerHeight = relati.getHeight();
            containerWidth = relati.getWidth();
        }

    }

    private int getStatusBarHeight() {
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }
    //来保存用户的Login_id
    public void SaveLoginID(String key,String values){
        SharedPreferences sharedPreferences=getSharedPreferences("Anime_Login_id",MODE_PRIVATE);
        sharedPreferences.edit().putString(key,values).commit();
    }
    //用户退出时使用
    public  void exit(String name) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                ActivityUse.this, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ExitAppUtlis.getInstance().exit();
            }
        });
        dialog.getnobtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }
//一些提示的时候调用
    public    void hint(String name) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                ActivityUse.this, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        dialog.setisVisibility();

    }

    /**
     * 比例当用户输入卡号错误之后弹出提示，之后销毁当前页面需要调用此方法
     * @param name
     * @param handler
     */
    public  void hint(String name, final Handler handler) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                ActivityUse.this, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                handler.sendMessage(handler.obtainMessage(EXETS));
                dialog.dismiss();
            }
        });
        dialog.setisVisibility();

    }

    /**
     * 传入Handerl值更便于操作
     * @param name
     * @param handler
     * @param i
     */
    public  void hint(String name, final Handler handler,final int i) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                ActivityUse.this, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                handler.sendMessage(handler.obtainMessage(i));
                dialog.dismiss();
            }
        });
        dialog.setisVisibility();

    }

    /**
     * 专用于版本号提示框
     * @param name
     * @param handler
     * @param i
     */
    public  void hintvision(String name, final Handler handler,final int i) {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(
                ActivityUse.this, name);
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                handler.sendMessage(handler.obtainMessage(i));
                dialog.dismiss();
            }
        });
        dialog.getnobtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendMessage(handler.obtainMessage(i));
                dialog.dismiss();
            }
        });

    }
    //判断网络是否链接
    public int  setConnectivityManager(){
        ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info==null){
          return 0;
        }else{
           return 1;
        }

    }



    //获取当前时间
    public static String getTime()
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String startDate = formatter.format(curDate);
        return startDate;
    }
    //分发的时间
    public static String getCurrentDay()
    {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String startDate = formatter.format(curDate);
        return startDate;
    }
    //获取当前日期
    public static String getDateTime()
    {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String startDate = formatter.format(curDate);
        return startDate;
    }

    //创建桌面快捷方式
    public void createShortCut(){
        Intent launintent=new Intent();
        final String action=launintent.getAction();
        Intent resultIntent=new Intent();
        //设置快捷方式图
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this,R.mipmap.lz_kuaijie));
        resultIntent.putExtra("duplicate",false);
        Intent shortcuintent=new Intent();

        //设置点击快捷方式启动的Activity因为是从lanucher中启动的所以包名类名要写一致
        shortcuintent.setComponent(new ComponentName(getPackageName(),getPackageName()+"."+ MyDoorPreferTrue.class.getSimpleName()));
      //设置启动模式
        shortcuintent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_NEW_TASK);
        //启动Intent
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcuintent);

        //设置快捷方式的名称
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"开门");
        // 长按方式添加快捷方式----->即被动的Action方式。
        if (Intent.ACTION_CREATE_SHORTCUT.equals(action)){
            setResult(RESULT_OK,resultIntent);
            finish();
        }else{
            resultIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

            sendBroadcast(resultIntent);
        }


    }


}
